package com.cnc.common.web.util;


import org.jboss.resteasy.api.validation.ResteasyViolationException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 作者： cnc
 * 创建时间：2017-09-28.
 * 版本：1.0
 */
public class ValidationUtils {

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> void validate(T obj){
        Set<ConstraintViolation<T>> set =  validator.validate(obj,Default.class);
        if(set != null && set.size()>0)
            throw  new ResteasyViolationException(set);
    }


    public static <T> String validateEntity(T obj){
        StringBuffer result = null;
        Set<ConstraintViolation<T>> set = validator.validate(obj,Default.class);
        if(set != null && set.size() > 0){
            result = new StringBuffer();
            for(ConstraintViolation<T> cv : set){
                result.append(cv.getMessage());
            }
        }
        return result == null? null : result.toString();
    }

    public static <T> String validateProperty(T obj,String propertyName){
        StringBuffer result = null;
        Set<ConstraintViolation<T>> set = validator.validateProperty(obj,propertyName,Default.class);
        if(set != null && set.size() > 0){
            Map<String,String> errorMsg = new HashMap<String,String>();
            for(ConstraintViolation<T> cv : set){
                result.append(cv.getMessage());
            }
        }
        return result == null? null : result.toString();
    }
}
